package com.cat.slidingWindow;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/swap-for-longest-repeated-character-substring/description/
 * @create 2025/9/17 20:02
 * @since JDK17
 */

public class Solution40 {
    public int maxRepOpt1(String text) {
        char[] s = text.toCharArray();
        int n = s.length, ans = 0;
        int[] h = new int[128], cnt = new int[128];
        for (int i = 0; i < n; i++) {
            h[s[i]]++;
        }
        for (int l = 0, r = 0; r < n; r++) {
            cnt[s[r]]++;    // 进入窗口
            while (r - l + 1 - cnt[s[l]] > 1) { // 以s[l]作为相同的字符
                cnt[s[l++]]--;  // 退出窗口
            }
            int t = cnt[s[l]] < h[s[l]] ? 1 : 0;    // 可以替换
            if (cnt[s[l]] == r - l + 1) {  // 全部都一样
                ans = Math.max(ans, r - l + 1 + t);
            } else {    // 并非完全一样
                ans = Math.max(ans, r - l + t);
            }
        }

        return ans;
    }
}
